<template>
	<div class='fx'>
		<Input v-model:value='modelValue' :p='p' :disabled='disabled' @input='onInput' :size='size' />
		<div class='ml5'>
			<img :src='codeSrc' class='cp nowrap h' @click='onCode' alt='图片验证码'/>
		</div>
	</div>
</template>

<script>
	import { ref, watch } from 'vue'
	const Input 		= $.lazy(()=>import('@antd/form/input.vue'))
	const Button 		= $.lazy(()=>import('@antd/button.vue'))
	
	export default{
		components:{ Input, Button, Image},
		props:{
			value 		: String,
			name 		: String,
			label 		: String,
			form 		: Object,
			p			: { type:String },
			disabled 	: Boolean,
			size 		: { type:[Number, String], default: 'small'},
			src 		: String,
			api 		: String,
			formRef 	: Object,
			uidStr 		: { type:String, default:'uuid' },
			imgStr 		: { type:String, default:'img' }
		},
		emits:{
			change:null,
			blur:null,
			click:null,
			'update:value':null
		},
		setup(props, ctx){
			const { formRef, name, src, api, value, imgStr, uidStr } = props
			const modelValue = ref(value)
			const codeSrc = ref(src)
			
			watch(()=>props.src, value => codeSrc.value = value )
			
			watch(()=>props.value, value => modelValue.value = value )
			
			const onCode = () => {
				if(api){
					$http.pull(null, api, { token:false }).then( data => {
						const img = data[imgStr]
						codeSrc.value = img.includes('base64') ? img : (`data:image/jpg;base64,${img}`).replace(/[\r\n]/g,'')
						if(data[uidStr]){
							formRef.setValue({ [uidStr]: data[uidStr] })
						}
					})
				}else{
					ctx.emit('click')
				}
			}
			
			onCode()
			
			return {
				modelValue,
				codeSrc,
				onInput : value => {
					modelValue.value = value
					ctx.emit('update:value', value)
					ctx.emit('change', { value, row:{ [name]: value } })
				},
				onCode
			}
		}
	}
</script>